package xin.shaozeming.base.common.quartz;

import lombok.extern.log4j.Log4j2;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import xin.shaozeming.base.common.Enum.base.QuartzState;
import xin.shaozeming.base.po.QuartzPO;
import xin.shaozeming.base.service.QuartzService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author: 邵泽铭
 * @date: 2019/10/17
 * @description:
 **/

@Log4j2
@Configuration
public class DynamicQuartzScheduler {
    @Resource
    private Scheduler scheduler;


    @Resource
    private QuartzService quartzService;


    private static  final String job_key="job";
    private static  final String trigger_key="trigger";
    private static  final String package_mae="xin.shaozeming.base.common.quartz.job.";
    /**
     * 开始执行所有任务
     *
     * @throws SchedulerException
     */
    public void startAllJob() throws SchedulerException {
        List<QuartzPO> list = quartzService.list();
        if(list!=null){
            list.forEach(item->{
                try {
                    if(QuartzState.START.getCode().equals(item.getQuartzState())){
                        startJob(item.getId(),item.getCron() ,item.getQuartzName());
                    }
                } catch (Exception e) {
                     log.error("定时器{}启动失败 {}",item.getQuartzName(), e.getMessage() );
                     item.setQuartzState(QuartzState.STOP.getCode());
                     quartzService.updateById(item);
                }
            });
        }
        scheduler.start();
    }

    /**
     * 获取Job信息
     *
     * @param name
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(Integer name) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(trigger_key+name);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某个任务的执行时间
     *
     * @param name
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(Integer name, String time) throws SchedulerException {
        Date date = null;

        TriggerKey triggerKey = new TriggerKey(trigger_key+name);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(trigger_key+name)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * 暂停所有任务
     *
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停某个任务
     *
     * @param name
     * @throws SchedulerException
     */
    public void pauseJob(Integer name) throws SchedulerException {
        JobKey jobKey = new JobKey(job_key+name);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     *
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     *
     * @param name
     * @throws SchedulerException
     */
    public void resumeJob(Integer name) throws SchedulerException {
        JobKey jobKey = new JobKey(job_key+name);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @throws SchedulerException
     */
    public void deleteJob(Integer name) throws SchedulerException {
        JobKey jobKey = new JobKey(job_key+name);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    public void startJob(Integer id,String cron,String className) throws Exception {
        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例

        Class<Job> aClass = (Class<Job>) Class.forName(package_mae + className);

        JobDetail jobDetail = JobBuilder.newJob(aClass).withIdentity(job_key+id).build();
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(trigger_key+id)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }



}
